package com.learn.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learn.account.entity.AccountTbl;
import com.learn.account.mapper.AccountTblMapper;
import com.learn.account.service.IAccountTblService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhaofa
 * @since 2019-11-12
 */
@Service
public class AccountTblServiceImpl extends ServiceImpl<AccountTblMapper, AccountTbl> implements IAccountTblService {
    @Resource
    private AccountTblMapper accountTblMapper;
    private static final String ERROR_USER_ID = "1002";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void reduce(String userId, BigDecimal num) {
        QueryWrapper<AccountTbl> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        AccountTbl account = accountTblMapper.selectOne(queryWrapper);
        if (account != null) {
            account.setMoney(account.getMoney().subtract(num));
            accountTblMapper.update(account, queryWrapper);
        } else {
            AccountTbl accountTbl = new AccountTbl();
            accountTbl.setUserId(userId);
            accountTbl.setMoney(num);
            accountTblMapper.insert(accountTbl);
        }

        if (ERROR_USER_ID.equals(userId)) {
            throw new RuntimeException("account branch exception");
        }
    }
}
